package com.ruoyi.user.service.impl;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easemob.im.server.model.EMUser;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.huanxing.EMServiceUtil;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.ProjectConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtil;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.common.utils.parameter.DistanceUtil;
import com.ruoyi.common.utils.parameter.ShareCodeUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.dynamic.domain.UserDynamic;
import com.ruoyi.dynamic.domain.UserParty;
import com.ruoyi.dynamic.mapper.UserDynamicMapper;
import com.ruoyi.dynamic.mapper.UserPartyMapper;
import com.ruoyi.framework.security.auth.JWTUser;
import com.ruoyi.framework.security.auth.JwtUtil;
import com.ruoyi.framework.security.auth.RequestContext;
import com.ruoyi.order.domain.OrderInfo;
import com.ruoyi.order.mapper.OrderEvaluateMapper;
import com.ruoyi.order.mapper.OrderInfoMapper;
import com.ruoyi.order.pojo.AppOrderEvaluateDTO;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.mapper.PriceSettingMapper;
import com.ruoyi.thread.TaskAsync;
import com.ruoyi.user.domain.FileAttachment;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserBlacklist;
import com.ruoyi.user.domain.UserCapitalFlow;
import com.ruoyi.user.domain.UserConcern;
import com.ruoyi.user.domain.UserConversationRecord;
import com.ruoyi.user.domain.UserExtend;
import com.ruoyi.user.domain.UserProject;
import com.ruoyi.user.domain.UserRelation;
import com.ruoyi.user.domain.UserSealTime;
import com.ruoyi.user.domain.UserThirdParty;
import com.ruoyi.user.domain.UserTotalCapital;
import com.ruoyi.user.domain.UserUnlockWechat;
import com.ruoyi.user.mapper.FileAttachmentMapper;
import com.ruoyi.user.mapper.UserBlacklistMapper;
import com.ruoyi.user.mapper.UserConversationRecordMapper;
import com.ruoyi.user.mapper.UserExtendMapper;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.mapper.UserProjectMapper;
import com.ruoyi.user.mapper.UserRelationMapper;
import com.ruoyi.user.mapper.UserTotalCapitalMapper;
import com.ruoyi.user.mapper.UserUnlockWechatMapper;
import com.ruoyi.user.pojo.AppConsultantAuth;
import com.ruoyi.user.pojo.AppRegister;
import com.ruoyi.user.pojo.AppUserDetail;
import com.ruoyi.user.pojo.AppUserInfo;
import com.ruoyi.user.pojo.AppUserParam;
import com.ruoyi.user.pojo.AppUserPersonal;
import com.ruoyi.user.pojo.AppWechatVO;
import com.ruoyi.user.pojo.AppWhoHaveIsee;
import com.ruoyi.user.service.AppUserService;
import com.ruoyi.user.service.IUserCapitalFlowService;
import com.ruoyi.user.service.IUserConcernService;
import com.ruoyi.user.service.IUserDataStatisticsService;
import com.ruoyi.user.service.IUserExtendService;
import com.ruoyi.user.service.IUserSealTimeService;
import com.ruoyi.user.service.IUserThirdPartyService;
import com.ruoyi.user.service.IUserTotalCapitalService;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 	用户Service
 * @author DEREK
 *
 */
@Service
@Slf4j
public class AppUserServiceImpl implements AppUserService {

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private IUserSealTimeService userSealTimeService;
	@Autowired
	private JwtUtil tokenUtils;
	@Autowired
	private IUserExtendService userExtendService;
	@Autowired
	private IUserThirdPartyService userThirdPartyService;
	@Autowired
	private UserRelationMapper userRelationMapper;
	@Autowired
	private TaskAsync taskAsync;
	@Autowired
	private FileAttachmentMapper fileAttachmentMapper;
	@Autowired
	private IUserConcernService userConcernService;
	@Autowired
	private EMServiceUtil eMServiceUtil;
	@Autowired
	private UserBlacklistMapper userBlacklistMapper;
	@Autowired
	private UserTotalCapitalMapper userTotalCapitalMapper;
	@Autowired
	private UserProjectMapper userProjectMapper;
	@Autowired
	private OrderEvaluateMapper orderEvaluateMapper;
	@Autowired
	private IUserCapitalFlowService userCapitalFlowService;
	@Autowired
	private IUserTotalCapitalService userTotalCapitalService;
	@Autowired
	private UserDynamicMapper userDynamicMapper;
	@Autowired
	private UserUnlockWechatMapper userUnlockWechatMapper;
	@Autowired
	private UserConversationRecordMapper userConversationRecordMapper;
	@Autowired
	private UserPartyMapper userPartyMapper;
	@Autowired
	private UserExtendMapper userExtendMapper;
	@Autowired
	private IUserDataStatisticsService userDataStatisticsService;
	@Autowired
	private OrderInfoMapper orderInfoMapper;

	private String exampleCode = "518186";


	@Override
	public AjaxResult login(String mobile,String mobileCode,Integer type,HttpServletRequest request){
		if(0 == type) {
			boolean right = false;
			Object savedMobile = redisUtil.get(ProjectConstant.RedisKey.MOBILE_CODE.getKeyPrefix() +"_"+ 1 + "_" + mobileCode);
			log.info("取缓存中的验证码信息:{}",JSON.toJSONString(savedMobile));
			if (savedMobile != null && mobile.equals(savedMobile.toString())) {
				right = true;
			}
			if(exampleCode.equals(mobileCode)){
				right = true;
			}
			if (!right) {
				return AjaxResult.error("验证码不一致");
			}
		}
		AppRegister result = new AppRegister();
		try {
			String deviceName = request.getHeader("deviceName");
			String clientType = request.getHeader("clientType");
			Integer versionCode = request.getIntHeader("versionCode");

			//业务操作
			User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone", mobile));
			if(null == user) {
				// 注册判断 是否已经注册过且注销
				User one = userMapper.selectOne(new LambdaQueryWrapper<User>().like(User::getPhone, mobile)
						.eq(User::getEnabled, 4).select(User::getId,User::getServiceType).orderByDesc(User::getServiceType).last("limit 1"));
				if(null != one && StringUtils.isNotEmpty(one.getServiceType())) {
					Long now = Long.valueOf(DateUtils.format(new Date(), "yyyyMMddHHmm"));
					Long time = Long.valueOf(one.getServiceType());
					if(now < time) {
						return AjaxResult.error("注销后24小时方可重新注册");
					}
				}
				user = new User();
				user.setPhone(mobile);
				user.setEnabled(1);
				user.setBaseInfoComplete(0);
				user.setRegisterTime(new Date());
				user.setMacAddress(clientType);
				user.setDeviceName(deviceName);
				user.setSex("M");
				user.setClientVersion(String.valueOf(versionCode));
				// 添加默认头像和昵称
				user.setNickName("用户"+CommonUtil.getRandomUserName());
				user.setHeadPic(ProjectConstant.HEAD_PIC);
				if(1 == type) {
					return AjaxResult.error("账号不存在,请用短信验证码注册");
					//user.setPassword(Md5Utils.hash(mobile.substring(5, mobile.length())));
				}
				userMapper.insert(user);
				result.setUserId(user.getId());
				result.setMobile(mobile);
				result.setNickName(user.getName());
				result.setHeadPic(user.getHeadPic());
				result.setSex(user.getSex());

				// 新增用户 统计
				//taskAsync.completeUserInfoStatistics(1,user, userService, userDataStatisticsService);
				//return AjaxResult.success("获取成功",result);
			}else {//登录
				// 验证密码
				if(1 == type) {
					String userPwd = Md5Utils.hash(mobileCode);
					if(!userPwd.equals(user.getPassword())) {
						return AjaxResult.error("密码不正确");
					}
				}
				//判断是否禁用或者关闭小黑屋
				if(2 == user.getEnabled()) {
					//return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结",sealEntity(user),user.getId());
					return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结");
				}
				UserSealTime userSealTime = userSealTimeService.getOne(new QueryWrapper<UserSealTime>().eq("user_id", user.getId()).eq("type", 1).last("limit 0,1"));
				if(null != userSealTime) {
					if(new Date().before(userSealTime.getExpireTime())) {
						String content = "经用户举报，您已违反平台相关规定，现处以封号处罚。-解封时间"+DateUtils.format(userSealTime.getExpireTime(), "yyyy-MM-dd");
						//return AjaxResult.error(500107,content,sealEntity(user),user.getId());
						return AjaxResult.error(500107,content);
					}
				}
				if(null != user.getBirthday()) {
					int age = CommonUtil.getAge(user.getBirthday());
					if(age < 18) {
						return AjaxResult.error("未成年禁止使用(你必须满18岁才能使用，期待你满18岁的那一天)");
					}
				}
				//result.setHeadPic(CommonUtil.addAddress800(headPic));
				//更新登录时间
				user.setLoginTime(new Date());
				user.setMacAddress(clientType);
				user.setDeviceName(deviceName);
				userMapper.updateById(user);
				result.setVip(user.getVip());
				result.setVipLevel(user.getVipLevel());
				result.setSex(user.getSex());
				result.setRealPersonAuth(user.getRealPersonAuth());
				result.setNickName(user.getNickName());
				if(user.getBaseInfoComplete() == 1) {
					result.setIsBinding(0);
				}
				if(StringUtils.isNotEmpty(user.getInteName())) {
					result.setIsLable(0);
				}
				// 记录登录日志
				//taskAsync.userLoginLog(user.getId(), deviceName, request, userService,userNoticeService,"",null,null);
				//				UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
				//				if(null == userExtend || StringUtils.isEmpty(userExtend.getEmUsername()) || StringUtils.isEmpty(userExtend.getEmPassword())) {
				//					return AjaxResult.error("未注册IM");
				//				}
			}
			result.setHeadPic(user.getHeadPic());
			String token = tokenUtils.sign(user.getId().toString(),user.getNickName(),user.getPhone());
			//redisUtil.set(user.getId()+"token", token);
			// 注册环信账号
			//String nickName = CommonUtil.getRandomUserName();
			//taskAsync.registerEmAccount(user.getId(), request.getHeader("deviceId"), nickName);
			UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
			if(Objects.isNull(userExtend)) {
				userExtend = new UserExtend();
				String nickName = CommonUtil.getRandomUserName();
				EMUser createUser = eMServiceUtil.createUser(nickName);
				if(null == createUser) {
					return AjaxResult.error("登录失败");
				}
				// 用户扩展表
				userExtend.setUserId(user.getId());
				userExtend.setInviteCode(ShareCodeUtils.toSerialCode(user.getId()));
				userExtend.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
				userExtend.setEmUsername(createUser.getUsername());
				userExtend.setEmPassword(createUser.getUsername());
				userExtend.setDeviceId(request.getHeader("deviceId"));
				userExtendService.save(userExtend);
			}else {
				if(StringUtils.isEmpty(userExtend.getEmUsername())) {
					String nickName = CommonUtil.getRandomUserName();
					EMUser createUser = eMServiceUtil.createUser(nickName);
					if(null == createUser) {
						return AjaxResult.error("登录失败");
					}
					userExtend.setEmUsername(createUser.getUsername());
					userExtend.setEmPassword(createUser.getUsername());
				}
				userExtend.setDeviceId(request.getHeader("deviceId"));
				userExtendService.updateById(userExtend);
			}
			result.setEmUsername(userExtend.getEmUsername());
			result.setEmPassword(userExtend.getEmPassword());
			result.setUserId(user.getId());
			result.setToken(token);
			result.setMobile(mobile);
			result.setBaseInfoComplete(user.getBaseInfoComplete());
			if(null != user.getBirthday()) {
				result.setAge(CommonUtil.getAge(user.getBirthday()));
			}else {
				result.setAge(22);
			}
			// 查询用户头像
		} catch (Exception e) {
			e.printStackTrace();
			log.error("方法：login-手机号码登录异常，",e);
			return AjaxResult.error("网络繁忙");
		}
		return AjaxResult.success("获取成功",result);
	}

	@Override
	public AjaxResult oneClickLogin(String accessToken,HttpServletRequest request){
		AppRegister result = new AppRegister();
		try {
			String mobile = accessToken;//GetMobile.getMobileByToken(accessToken);
			if(StringUtils.isEmpty(mobile)) {
				return AjaxResult.error(450,"token失效");
			}
			String deviceName = request.getHeader("deviceName");
			String clientType = request.getHeader("clientType");
			Integer versionCode = request.getIntHeader("versionCode");

			//业务操作
			User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone", mobile));
			if(null == user) {
				user = new User();
				user.setPhone(mobile);
				user.setEnabled(1);
				user.setBaseInfoComplete(0);
				user.setRegisterTime(new Date());
				user.setMacAddress(clientType);
				user.setDeviceName(deviceName);
				user.setSex("M");
				user.setClientVersion(String.valueOf(versionCode));
				// 添加默认头像和昵称
				user.setNickName("用户"+CommonUtil.getRandomUserName());
				user.setHeadPic(ProjectConstant.HEAD_PIC);
				userMapper.insert(user);
				result.setUserId(user.getId());
				result.setMobile(mobile);
				result.setNickName(user.getName());
				result.setHeadPic(user.getHeadPic());
				result.setSex(user.getSex());
				// 新增用户 统计
				//taskAsync.completeUserInfoStatistics(1,user, userService, userDataStatisticsService);
				//return AjaxResult.success("获取成功",result);

			}else {//登录
				//判断是否禁用或者关闭小黑屋
				if(2 == user.getEnabled()) {
					//return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结",sealEntity(user),user.getId());
					return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结");
				}
				UserSealTime userSealTime = userSealTimeService.getOne(new QueryWrapper<UserSealTime>().eq("user_id", user.getId()).eq("type", 1).last("limit 0,1"));
				if(null != userSealTime) {
					if(new Date().before(userSealTime.getExpireTime())) {
						String content = "经用户举报，您已违反平台相关规定，现处以封号处罚。-解封时间"+DateUtils.format(userSealTime.getExpireTime(), "yyyy-MM-dd");
						//return AjaxResult.error(500107,content,sealEntity(user),user.getId());
						return AjaxResult.error(500107,content);
					}
				}
				if(null != user.getBirthday()) {
					int age = CommonUtil.getAge(user.getBirthday());
					if(age < 18) {
						return AjaxResult.error("未成年禁止使用(你必须满18岁才能使用，期待你满18岁的那一天)");
					}
				}
				//result.setHeadPic(CommonUtil.addAddress800(headPic));
				//更新登录时间
				user.setLoginTime(new Date());
				user.setMacAddress(clientType);
				user.setDeviceName(deviceName);
				userMapper.updateById(user);
				result.setVip(user.getVip());
				result.setSex(user.getSex());
				result.setRealPersonAuth(user.getRealPersonAuth());
				result.setNickName(user.getNickName());
				if(user.getBaseInfoComplete() == 1) {
					result.setIsBinding(0);
				}
				if(StringUtils.isNotEmpty(user.getInteName())) {
					result.setIsLable(0);
				}
			}
			result.setHeadPic(user.getHeadPic());
			String token = tokenUtils.sign(user.getId().toString(),user.getNickName(),user.getPhone());
			//redisUtil.set(user.getId()+"token", token);
			// 注册环信账号
			//String nickName = CommonUtil.getRandomUserName();
			//taskAsync.registerEmAccount(user.getId(), request.getHeader("deviceId"), nickName);
			UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
			if(Objects.isNull(userExtend)) {
				userExtend = new UserExtend();
				String nickName = CommonUtil.getRandomUserName();
				EMUser createUser = eMServiceUtil.createUser(nickName);
				if(null == createUser) {
					return AjaxResult.error("登录失败");
				}
				// 用户扩展表
				userExtend.setUserId(user.getId());
				userExtend.setInviteCode(ShareCodeUtils.toSerialCode(user.getId()));
				userExtend.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
				userExtend.setEmUsername(createUser.getUsername());
				userExtend.setEmPassword(createUser.getUsername());
				userExtend.setDeviceId(request.getHeader("deviceId"));
				userExtendService.save(userExtend);
			}else {
				if(StringUtils.isEmpty(userExtend.getEmUsername())) {
					String nickName = CommonUtil.getRandomUserName();
					EMUser createUser = eMServiceUtil.createUser(nickName);
					if(null == createUser) {
						return AjaxResult.error("登录失败");
					}
					userExtend.setEmUsername(createUser.getUsername());
					userExtend.setEmPassword(createUser.getUsername());
				}
				userExtend.setDeviceId(request.getHeader("deviceId"));
				userExtendService.updateById(userExtend);
			}
			result.setEmUsername(userExtend.getEmUsername());
			result.setEmPassword(userExtend.getEmPassword());
			result.setUserId(user.getId());
			result.setToken(token);
			result.setMobile(mobile);
			result.setBaseInfoComplete(user.getBaseInfoComplete());
			if(null != user.getBirthday()) {
				result.setAge(CommonUtil.getAge(user.getBirthday()));
			}else {
				result.setAge(22);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
		return AjaxResult.success("获取成功",result);

	}

	@Override
	public AjaxResult completeUserInfo(AppRegister appRegister, HttpServletRequest request) {
		long start = System.currentTimeMillis();
		if(!redisUtil.setIfAbsentCustom("completeUserInfo:"+appRegister.getUserId(),1000)) {
			return AjaxResult.error("休息一下吧~");
		}
		try {
			User user = userMapper.selectById(appRegister.getUserId());
			if(null == user) {
				return AjaxResult.error("用户不存在");
			}
			//检查昵称是否存在
			Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getNickName, appRegister.getNickName()).last(" limit 1"));
			if(null != count && count > 0) {
				return AjaxResult.error("昵称被占用，请重新输入");
			}
			String deviceName = request.getHeader("deviceName");
			String clientType = request.getHeader("clientType");
			Integer versionCode = request.getIntHeader("versionCode");
			
			if(StringUtils.isNotEmpty(user.getNickName())) {
				user.setNickName(appRegister.getNickName());
			}
			user.setSex(appRegister.getSex());
			user.setHeight(appRegister.getHeight());
			user.setBodyWeight(appRegister.getBodyWeight());
			user.setProfessional(appRegister.getProfessional());
			user.setLoginCityCode(appRegister.getCityCode());
			user.setLoginCityName(appRegister.getCity());
			user.setLoginPointX(appRegister.getLongitude());
			user.setLoginPointY(appRegister.getLatitude());
			user.setWechat(appRegister.getWechat());
			//生日
			Date birthday = null;
			if(StringUtils.isNotEmpty(appRegister.getBirthday())) {
				birthday = DateUtil.formatDate("yyyy-MM-dd", appRegister.getBirthday());
				if(null != birthday) {
					user.setBirthday(birthday);
				}
			}
			user.setAge(CommonUtil.getAge(user.getBirthday()));
			//处理星座
			SimpleDateFormat df = new SimpleDateFormat("MM");
			SimpleDateFormat dfc = new SimpleDateFormat("dd");
			if(null != birthday) {
				user.setConstellation(DateUtil.constellation(Integer.valueOf(df.format(birthday)), Integer.valueOf(dfc.format(birthday))));
			}else {
				user.setConstellation(DateUtil.constellation(Integer.valueOf(df.format(new Date())), Integer.valueOf(dfc.format(new Date()))));
			}
			user.setHeadPic(appRegister.getHeadPic());
			user.setBaseInfoComplete(1);
			user.setLoginTime(new Date());
			user.setMacAddress(clientType);
			user.setClientVersion(String.valueOf(versionCode));
			user.setDeviceName(deviceName);
			user.setSignature("小哥哥快来撩我呀~");
			if(StringUtils.isEmpty(appRegister.getPassword())) {
				user.setPassword(Md5Utils.hash(user.getPhone().substring(5,user.getPhone().length())));
			}else {
				user.setPassword(Md5Utils.hash(appRegister.getPassword()));
			}
			userMapper.updateById(user);
			// 获取用户详细地址
			taskAsync.updUserDetailedAddress(user.getId(), user.getLoginPointX(), user.getLoginPointY());
			String token = tokenUtils.sign(user.getId().toString(),user.getNickName(),user.getPhone());
			redisUtil.set(user.getId()+"token", token);

			// 注册环信账号
			//			String nickName = CommonUtil.getRandomUserName();
			UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
			if(Objects.isNull(userExtend)) {
				userExtend = new UserExtend();
				String nickName = CommonUtil.getRandomUserName();
				taskAsync.registerEmAccount(nickName);
				// 用户扩展表
				userExtend.setUserId(user.getId());
				userExtend.setInviteCode(ShareCodeUtils.toSerialCode(user.getId()));
				userExtend.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
				userExtend.setEmUsername(nickName);
				userExtend.setEmPassword(nickName);
				userExtend.setDeviceId(request.getHeader("deviceId"));
				userExtendService.save(userExtend);
			}else {
				if(StringUtils.isEmpty(userExtend.getEmUsername())) {
					String nickName = CommonUtil.getRandomUserName();
					taskAsync.registerEmAccount(nickName);
					userExtend.setEmUsername(nickName);
					userExtend.setEmPassword(nickName);
				}
				userExtend.setDeviceId(request.getHeader("deviceId"));
				userExtendService.updateById(userExtend);
			}
			appRegister.setEmUsername(userExtend.getEmUsername());
			appRegister.setEmPassword(userExtend.getEmPassword());
			appRegister.setToken(token);
			appRegister.setMobile(user.getPhone());
			System.out.println("结束时间:"+(start - System.currentTimeMillis()));
			// 女性用户赠送VIP
			if("F".equalsIgnoreCase(user.getSex())) {
				// TODO 女性暂时不赠送VIP 0430 修改
				//				user.setVip(1);
				//				user.setVipExpireTime(DateUtils.getPastDateTimeYear(100, new Date(), 2));
				//				user.setInviteCount(10);
				//				user.setUnlockWechat(10);
				//				user.setChatCount(10);
				//				Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKWECHATCOUNT);
				//				if(null != object) {
				//					user.setUnlockWechat(Integer.valueOf(object.toString()));
				//				}
				//				Object object2 = redisUtil.get(ProjectConstant.platformConstant.UNLOCKCHATCOUNT);
				//				if(null != object2) {
				//					user.setChatCount(Integer.valueOf(object2.toString()));
				//				}
				//				userMapper.updateById(user);
			}else {
				boolean examineMode = isExamineMode();
				if(examineMode) {
					user.setVip(1);
					user.setVipExpireTime(DateUtils.getPastDateTime(1, new Date(), 2));
					user.setInviteCount(10);
					user.setUnlockWechat(10);
					user.setChatCount(10);
					user.setMessageCount(10);
					userMapper.updateById(user);
				}else {
					PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "男性聊天次数")
							.select(PriceSetting::getId,PriceSetting::getPriceName));
					if(null != set && StringUtils.isNotEmpty(set.getPriceName()) && Integer.valueOf(set.getPriceName()) > 0) {
						user.setChatCount(Integer.valueOf(set.getPriceName()));
						userMapper.updateById(user);
					}

				}
			}
			PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "非会员聊天条数")
					.select(PriceSetting::getId,PriceSetting::getPriceName));
			if(null != set && StringUtils.isNotEmpty(set.getPriceName()) && Integer.valueOf(set.getPriceName()) > 0) {
				user.setMessageCount(Integer.valueOf(set.getPriceName()));
				userMapper.updateById(user);
			}
			// 新女性/男性用户 定时推送消息
			taskAsync.joinMsgSendCron(user.getId(), new Date(), user.getSex());
			// 统计新增
			userDataStatisticsService.addStatistics(0, 1);
			return AjaxResult.success("请求成功",appRegister);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("方法：completeUserInfo -异常，",e);
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult wechatLogin(String unionId,String openId,HttpServletRequest request) {
		AppRegister result = new AppRegister();
		result.setUnionId(unionId);
		result.setOpenId(openId);
		String deviceName = request.getHeader("deviceName");
		String clientType = request.getHeader("clientType");
		Integer versionCode = request.getIntHeader("versionCode");
		try {
			UserThirdParty userThirdParty = userThirdPartyService.getInfoByUnionId(unionId);
			if(null == userThirdParty) {//没绑定
				//跳转到绑定页面
				result.setUserId(0L);
				result.setToken("");
				result.setMobile("");
				result.setBaseInfoComplete(0);
				result.setBindingMobile(1);
				result.setIsBinding(1);
				return AjaxResult.success("操作成功",result);
			}else {
				User user = userMapper.selectById(userThirdParty.getUserId());
				if(user != null && user.getBaseInfoComplete() > 0) {
					// 已经绑定过微信，则直接登录
					//判断是否禁用或者关闭小黑屋
					if(2 == user.getEnabled()) {
						//return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结",sealEntity(user),user.getId());
						return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结");
					}
					UserSealTime userSealTime = userSealTimeService.getOne(new QueryWrapper<UserSealTime>().eq("user_id", user.getId()).eq("type", 1).last("limit 0,1"));
					if(null != userSealTime) {
						if(new Date().before(userSealTime.getExpireTime())) {
							String content = "经用户举报，您已违反平台相关规定，现处以封号处罚。-解封时间"+DateUtils.format(userSealTime.getExpireTime(), "yyyy-MM-dd");
							//return AjaxResult.error(500108,content,null,user.getId());
							return AjaxResult.error(500108,content);
						}
					}
					if(null != user.getBirthday()) {
						int age = CommonUtil.getAge(user.getBirthday());
						if(age < 18) {
							return AjaxResult.error("未成年禁止使用(你必须满18岁才能使用，期待你满18岁的那一天)");
						}
					}
					// 生成第三方数据
					userThirdParty.setMobile(user.getPhone());
					userThirdParty.setNickName(user.getNickName());
					userThirdParty.setUpdateTime(new Date());
					userThirdPartyService.updateById(userThirdParty);
					String token = tokenUtils.sign(user.getId().toString(),CommonUtil.isEmpty(user.getNickName())?"":user.getNickName(),user.getPhone());
					//redisUtil.set(user.getId()+"token", token);

					// 生成环信账号
					//					String nickName = CommonUtil.getRandomUserName();
					//					taskAsync.registerEmAccount(user.getId(), request.getHeader("deviceId"), nickName);
					//					result.setEmUsername(nickName);
					//					result.setEmPassword(nickName);
					UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
					if(Objects.isNull(userExtend)) {
						userExtend = new UserExtend();
						String nickName = CommonUtil.getRandomUserName();
						EMUser createUser = eMServiceUtil.createUser(nickName);
						if(null == createUser) {
							return AjaxResult.error("登录失败");
						}
						// 用户扩展表
						userExtend.setUserId(user.getId());
						userExtend.setInviteCode(ShareCodeUtils.toSerialCode(user.getId()));
						userExtend.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
						userExtend.setEmUsername(createUser.getUsername());
						userExtend.setEmPassword(createUser.getUsername());
						userExtend.setDeviceId(request.getHeader("deviceId"));
						userExtendService.save(userExtend);
					}else {
						if(StringUtils.isEmpty(userExtend.getEmUsername())) {
							String nickName = CommonUtil.getRandomUserName();
							EMUser createUser = eMServiceUtil.createUser(nickName);
							if(null == createUser) {
								return AjaxResult.error("登录失败");
							}
							userExtend.setEmUsername(createUser.getUsername());
							userExtend.setEmPassword(createUser.getUsername());
						}
						userExtend.setDeviceId(request.getHeader("deviceId"));
						userExtendService.updateById(userExtend);
					}
					result.setEmUsername(userExtend.getEmUsername());
					result.setEmPassword(userExtend.getEmPassword());
					result.setUserId(user.getId());
					result.setToken(token);
					result.setMobile(user.getPhone());
					result.setBaseInfoComplete(user.getBaseInfoComplete());
					if(user.getBaseInfoComplete() == 1) {
						result.setIsBinding(0);
					}
					if(StringUtils.isNotEmpty(user.getInteName())) {
						result.setIsLable(0);
					}
					if(null != user.getBirthday()) {
						result.setAge(CommonUtil.getAge(user.getBirthday()));
					}else {
						result.setAge(null);
					}
					result.setHeadPic(user.getHeadPic());
					//更新登录时间
					user.setLoginTime(new Date());
					user.setMacAddress(clientType);
					user.setClientVersion(String.valueOf(versionCode));
					user.setDeviceName(deviceName);
					userMapper.updateById(user);
					result.setVip(user.getVip());
					result.setSex(user.getSex());
					result.setRealPersonAuth(user.getRealPersonAuth());
					result.setNickName(user.getNickName());
					// 记录登录日志
					//taskAsync.userLoginLog(user.getId(), deviceName, request, userService,userNoticeService,"",null,null);
					return AjaxResult.success("操作成功",result);
				}else {
					//没有绑定
					result.setUserId(0L);
					result.setToken("");
					result.setMobile("");
					result.setBaseInfoComplete(0);
					result.setIsBinding(1);
					return AjaxResult.success("操作成功",result);
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			log.error("方法：wechatLogin-微信登录异常，",e);
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult appleLogin(String appleId,HttpServletRequest request) {
		AppRegister result = new AppRegister();
		String deviceName = request.getHeader("deviceName");
		String clientType = request.getHeader("clientType");
		Integer versionCode = request.getIntHeader("versionCode");
		try {
			// 判断用户是否已经绑定appleId
			UserThirdParty userThirdParty = userThirdPartyService.getByAppleId(appleId);
			if(null == userThirdParty) {//未绑定
				//跳转到绑定页面
				result.setUserId(0L);
				result.setToken("");
				result.setMobile("");
				result.setBaseInfoComplete(0);
				result.setBindingMobile(1);
				result.setIsBinding(1);
				return AjaxResult.success("操作成功",result);
			}else {
				User user = userMapper.selectById(userThirdParty.getUserId());
				if(user != null && user.getBaseInfoComplete() > 0) {
					//判断是否禁用或者关闭小黑屋
					if(2 == user.getEnabled()) {
						return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结");
					}
					UserSealTime userSealTime = userSealTimeService.getOne(new QueryWrapper<UserSealTime>().eq("user_id", user.getId()).eq("type", 1).last("limit 0,1"));
					if(null != userSealTime) {
						if(new Date().before(userSealTime.getExpireTime())) {
							String content = "经用户举报，您已违反平台相关规定，现处以封号处罚。-解封时间"+DateUtils.format(userSealTime.getExpireTime(), "yyyy-MM-dd");
							return AjaxResult.error(500107,content);
						}
					}
					if(null != user.getBirthday()) {
						int age = CommonUtil.getAge(user.getBirthday());
						if(age < 18) {
							return AjaxResult.error("未成年禁止使用(你必须满18岁才能使用，期待你满18岁的那一天)");
						}
					}
					// 生成第三方数据
					userThirdParty.setMobile(user.getPhone());
					userThirdParty.setNickName(user.getNickName());
					userThirdParty.setUpdateTime(new Date());
					userThirdPartyService.updateById(userThirdParty);

					String token = tokenUtils.sign(user.getId().toString(),CommonUtil.isEmpty(user.getNickName())?"":user.getNickName(),user.getPhone());
					//redisUtil.set(user.getId()+"token", token);

					// 生成环信账号
					//					String nickName = CommonUtil.getRandomUserName();
					//					taskAsync.registerEmAccount(user.getId(), request.getHeader("deviceId"), nickName);
					//					result.setEmUsername(nickName);
					//					result.setEmPassword(nickName);
					UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
					if(Objects.isNull(userExtend)) {
						userExtend = new UserExtend();
						String nickName = CommonUtil.getRandomUserName();
						EMUser createUser = eMServiceUtil.createUser(nickName);
						if(null == createUser) {
							return AjaxResult.error("登录失败");
						}
						// 用户扩展表
						userExtend.setUserId(user.getId());
						userExtend.setInviteCode(ShareCodeUtils.toSerialCode(user.getId()));
						userExtend.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
						userExtend.setEmUsername(createUser.getUsername());
						userExtend.setEmPassword(createUser.getUsername());
						userExtend.setDeviceId(request.getHeader("deviceId"));
						userExtendService.save(userExtend);
					}else {
						if(StringUtils.isEmpty(userExtend.getEmUsername())) {
							String nickName = CommonUtil.getRandomUserName();
							EMUser createUser = eMServiceUtil.createUser(nickName);
							if(null == createUser) {
								return AjaxResult.error("登录失败");
							}
							userExtend.setEmUsername(createUser.getUsername());
							userExtend.setEmPassword(createUser.getUsername());
						}
						userExtend.setDeviceId(request.getHeader("deviceId"));
						userExtendService.updateById(userExtend);
					}
					result.setEmUsername(userExtend.getEmUsername());
					result.setEmPassword(userExtend.getEmPassword());
					result.setUserId(user.getId());
					result.setToken(token);
					result.setMobile(user.getPhone());
					result.setBaseInfoComplete(user.getBaseInfoComplete());
					if(user.getBaseInfoComplete() == 1) {
						result.setIsBinding(0);
					}
					if(StringUtils.isNotEmpty(user.getInteName())) {
						result.setIsLable(0);
					}
					if(null != user.getBirthday()) {
						result.setAge(CommonUtil.getAge(user.getBirthday()));
					}else {
						result.setAge(null);
					}
					// 查询用户头像
					result.setHeadPic(user.getHeadPic());
					//更新登录时间
					user.setLoginTime(new Date());
					user.setMacAddress(clientType);
					user.setDeviceName(deviceName);
					user.setClientVersion(String.valueOf(versionCode));
					userMapper.updateById(user);
					result.setVip(user.getVip());
					result.setSex(user.getSex());
					result.setRealPersonAuth(user.getRealPersonAuth());
					result.setNickName(user.getNickName());
					// 记录登录日志
					//taskAsync.userLoginLog(user.getId(), deviceName, request, userService,userNoticeService,"",null,null);
					return AjaxResult.success("操作成功",result);
				}else {
					//没有绑定
					result.setUserId(0L);
					result.setToken("");
					result.setMobile("");
					result.setBaseInfoComplete(0);
					result.setIsBinding(1);
					return AjaxResult.success("操作成功",result);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("方法：appleLogin-苹果授权登录异常，",e);
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult bindingMobile(String mobile,String mobileCode,String unionId,String openId,String appleId,HttpServletRequest request){
		AppRegister result = new AppRegister();
		String deviceName = request.getHeader("deviceName");
		String clientType = request.getHeader("clientType");
		Integer versionCode = request.getIntHeader("versionCode");
		try {
			boolean right = false;
			Object savedMobile = redisUtil.get(ProjectConstant.RedisKey.MOBILE_CODE.getKeyPrefix()+"_" + 2 + "_" + mobileCode);
			log.info("取缓存中的验证码信息:{}",JSON.toJSONString(savedMobile));
			if (savedMobile != null && mobile.equals(savedMobile.toString())) {
				right = true;
			}
			if(exampleCode.equals(mobileCode)){
				right = true;
			}
			if (!right) {
				return AjaxResult.error("验证码不一致");
			}
			UserThirdParty userThirdParty = null;
			String mobile1 = mobile;
			// 查询用户信息
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, mobile));
			if(StringUtils.isNotEmpty(unionId) && StringUtils.isNotEmpty(openId)) {//微信登录
				boolean flag = userThirdPartyService.isBindMobile(mobile,unionId);
				if(flag){
					return AjaxResult.error("该手机号码已被其他微信绑定");
				}
				userThirdParty = userThirdPartyService.getOne(new QueryWrapper<UserThirdParty>().and(func -> func.eq("mobile", mobile1).or().eq("union_id", unionId)));
				if(null == userThirdParty) {
					// 2.保存绑定关系
					userThirdParty = new UserThirdParty();
					userThirdParty.setNickName("");
					userThirdParty.setUnionId(unionId);
					userThirdParty.setOpenId(openId);
					userThirdParty.setCreateTime(new Date());
					if(null != user) {
						userThirdParty.setUserId(user.getId());
					}else {
						userThirdParty.setUserId(0L);
					}
					userThirdParty.setUpdateTime(new Date());
					userThirdPartyService.save(userThirdParty);
				}else {
					if(null != user) {
						userThirdParty.setUserId(user.getId());
					}else {
						userThirdParty.setUserId(0L);
					}
					userThirdParty.setUnionId(unionId);
					userThirdParty.setOpenId(openId);
					userThirdPartyService.updateById(userThirdParty);
				}
			}else if(StringUtils.isNotEmpty(appleId)){//苹果登录
				// 手机已经被绑定了
				boolean flag = userThirdPartyService.isBindMobile(mobile,appleId);
				if(flag){
					return AjaxResult.error("该手机号码已被其他Apple绑定");
				}
				userThirdParty = userThirdPartyService.getOne(new QueryWrapper<UserThirdParty>().and(func -> func.eq("mobile", mobile1).or().eq("apple_id", appleId)));
				if(null == userThirdParty) {
					// 2.保存绑定关系
					userThirdParty = new UserThirdParty();
					userThirdParty.setNickName("");
					userThirdParty.setAppleId(appleId);
					userThirdParty.setCreateTime(new Date());
					if(null != user) {
						userThirdParty.setUserId(user.getId());
					}else {
						userThirdParty.setUserId(0L);
					}
					userThirdParty.setUpdateTime(new Date());
					userThirdPartyService.save(userThirdParty);
				}else {
					if(null != user) {
						userThirdParty.setUserId(user.getId());
					}else {
						userThirdParty.setUserId(0L);
					}
					userThirdParty.setAppleId(appleId);
					userThirdPartyService.updateById(userThirdParty);
				}
			}else {
				return AjaxResult.error("未知客户端");
			}
			if(null != user && user.getBaseInfoComplete() > 0) {
				//判断是否禁用或者关闭小黑屋
				if(2 == user.getEnabled()) {
					return AjaxResult.error(500107,"经用户举报，您已严重违反平台相关规定，账号永久冻结");
				}
				UserSealTime userSealTime = userSealTimeService.getOne(new QueryWrapper<UserSealTime>().eq("user_id", user.getId()).eq("type", 1).last("limit 0,1"));
				if(null != userSealTime) {
					if(new Date().before(userSealTime.getExpireTime())) {
						String content = "经用户举报，您已违反平台相关规定，现处以封号处罚。-解封时间"+DateUtils.format(userSealTime.getExpireTime(), "yyyy-MM-dd");
						return AjaxResult.error(500107,content);
					}
				}
				if(null != user.getBirthday()) {
					int age = CommonUtil.getAge(user.getBirthday());
					if(age < 18) {
						return AjaxResult.error("未成年禁止使用(你必须满18岁才能使用，期待你满18岁的那一天)");
					}
					result.setAge(age);
				}
				//更新登录时间
				user.setLoginTime(new Date());
				user.setMacAddress(clientType);
				user.setDeviceName(deviceName);
				user.setClientVersion(String.valueOf(versionCode));
				userMapper.updateById(user);
				// 记录登录日志
				//taskAsync.userLoginLog(user.getId(), deviceName, request, userService,userNoticeService,"",null,null);
				if(user.getBaseInfoComplete() == 1) {
					result.setIsBinding(0);
				}
				if(StringUtils.isNotEmpty(user.getInteName())) {
					result.setIsLable(0);
				}
				String token = tokenUtils.sign(user.getId().toString(),user.getNickName(),user.getPhone());
				//redisUtil.set(user.getId()+"token", token);

				// 生成环信账号
				//				String nickName = CommonUtil.getRandomUserName();
				//				taskAsync.registerEmAccount(user.getId(), request.getHeader("deviceId"), nickName);
				//				result.setEmUsername(nickName);
				//				result.setEmPassword(nickName);
				UserExtend userExtend = userExtendService.getUserExtendByUserId(user.getId());
				if(Objects.isNull(userExtend)) {
					userExtend = new UserExtend();
					String nickName = CommonUtil.getRandomUserName();
					EMUser createUser = eMServiceUtil.createUser(nickName);
					if(null == createUser) {
						return AjaxResult.error("登录失败");
					}
					// 用户扩展表
					userExtend.setUserId(user.getId());
					userExtend.setInviteCode(ShareCodeUtils.toSerialCode(user.getId()));
					userExtend.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
					userExtend.setEmUsername(createUser.getUsername());
					userExtend.setEmPassword(createUser.getUsername());
					userExtend.setDeviceId(request.getHeader("deviceId"));
					userExtendService.save(userExtend);
				}else {
					if(StringUtils.isEmpty(userExtend.getEmUsername())) {
						String nickName = CommonUtil.getRandomUserName();
						EMUser createUser = eMServiceUtil.createUser(nickName);
						if(null == createUser) {
							return AjaxResult.error("登录失败");
						}
						userExtend.setEmUsername(createUser.getUsername());
						userExtend.setEmPassword(createUser.getUsername());
					}
					userExtend.setDeviceId(request.getHeader("deviceId"));
					userExtendService.updateById(userExtend);
				}
				result.setEmUsername(userExtend.getEmUsername());
				result.setEmPassword(userExtend.getEmPassword());
				result.setUserId(user.getId());
				result.setToken(token);
				result.setMobile(mobile);
				result.setBaseInfoComplete(user.getBaseInfoComplete());
				// 查询用户头像
				result.setHeadPic(user.getHeadPic());
				result.setVip(user.getVip());
				result.setSex(user.getSex());
				result.setRealPersonAuth(user.getRealPersonAuth());
				result.setNickName(user.getNickName());
				result.setPhone(user.getPhone());
			}else{
				// 新增用户 统计
				//taskAsync.completeUserInfoStatistics(1,user, userService, userDataStatisticsService);
				result.setIsBinding(1);
				if(null == user) {
					user = new User();
					user.setPhone(mobile);
					user.setMacAddress(clientType);
					user.setDeviceName(deviceName);
					user.setClientVersion(String.valueOf(versionCode));
					userMapper.insert(user);
				}else {
					user.setMacAddress(clientType);
					user.setDeviceName(deviceName);
					user.setClientVersion(String.valueOf(versionCode));
					userMapper.updateById(user);
				}
			}
			// 完善绑定关系
			userThirdParty.setUserId(user.getId());
			userThirdParty.setNickName(user.getNickName());
			userThirdParty.setMobile(mobile);
			userThirdParty.setUpdateTime(new Date());
			userThirdPartyService.updateById(userThirdParty);
			result.setUserId(user.getId());
			result.setMobile(mobile);
		}catch (Exception e) {
			e.printStackTrace();
			log.error("方法：bindingMobile-绑定手机号码异常，",e);
			return AjaxResult.error("网络繁忙");
		}
		return AjaxResult.success("获取成功",result);
	}

	@Override
	public AjaxResult addUserPurpose(String name) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = new User();
			user.setId(loginUserId);
			user.setInteName(name);
			userMapper.updateById(user);
		}catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult bindInviteCode(String inviteCode) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			UserExtend userExtend = userExtendService.getOne(new LambdaQueryWrapper<UserExtend>().eq(UserExtend::getInviteCode, inviteCode)
					.select(UserExtend::getId,UserExtend::getUserId));
			if(null == userExtend) {
				return AjaxResult.error("邀请码不存在");	
			}
			Integer count = userRelationMapper.selectCount(new LambdaQueryWrapper<UserRelation>().eq(UserRelation::getUserId, loginUserId));
			if(count > 0) {
				return AjaxResult.error("你已经绑定上级用户");
			}
			UserRelation userRelation = new UserRelation();
			userRelation.setUserId(loginUserId);
			userRelation.setParentUserId(userExtend.getUserId());
			userRelation.setIsEffect("1");
			userRelation.setType(1);
			userRelationMapper.insert(userRelation);
		}catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult updUserLongitude(BigDecimal longitude, BigDecimal latitude,String city,Integer cityCode,HttpServletRequest request) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("city", city);
		map.put("longitude", longitude);
		map.put("latitude", latitude);
		try {
			taskAsync.update_user_positionn(city, loginUserId, longitude, latitude,cityCode, request);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("方法：updUserLongitude-更需要用户经纬度异常，",e);
		}
		return AjaxResult.success("成功",map);
	}

	@Override
	public AjaxResult userDetail(Long userId, BigDecimal longitude,BigDecimal latitude,HttpServletRequest request) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User currUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
				.select(User::getId,User::getLoginPointX,User::getLoginPointY,User::getEnabled));
		if(null == currUser) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if(2 == currUser.getEnabled()) {
			return AjaxResult.error(50010,"请重新登录");
		}
		try {
			System.out.println("个人主页经度："+longitude);
			System.out.println("个人主页纬度："+latitude);
			if(null == longitude || null == latitude) {
				longitude = currUser.getLoginPointX()==null?new BigDecimal("112"):currUser.getLoginPointX();
				latitude = currUser.getLoginPointY()==null?new BigDecimal("28"):currUser.getLoginPointY();
				System.out.println("用户本来的经度："+currUser.getLoginPointX());
				System.out.println("用户本来的纬度："+currUser.getLoginPointY());
			}
			if(null != userId) {
				taskAsync.updateUserVip(userId);
				taskAsync.updateUserStatus(loginUserId);
			}
			AppUserDetail user = userMapper.userDetail(loginUserId, userId,longitude,latitude);
			if(null == user) {
				return AjaxResult.error("用户不存在");
			}
			if(2 == user.getEnabled()) {
				return AjaxResult.error("对方账号已被封禁，无法查看主页");
			}else if(4 == user.getEnabled()) {
				return AjaxResult.error("对方账号已注销，无法查看主页");
			}
			UserSealTime userSealTime = userSealTimeService.getOne(new QueryWrapper<UserSealTime>().eq("user_id", userId).eq("type", 1).last("limit 0,1"));
			if(null != userSealTime) {
				if(new Date().before(userSealTime.getExpireTime())) {
					return AjaxResult.error("对方账号已被封禁，无法查看主页");
				}
			}
			// 是否拉黑
			Integer count = userBlacklistMapper.selectCount(new LambdaQueryWrapper<UserBlacklist>().eq(UserBlacklist::getUserId, loginUserId)
					.eq(UserBlacklist::getPullBlackUserId, userId).eq(UserBlacklist::getEnabled, 1));
			user.setIsBack(count);
			//处理年龄
			if(user.getBirthday() != null) {
				user.setAge(CommonUtil.getAge(user.getBirthday()));
			}else {
				user.setAge(22);
			}
			// 处理距离
			user.setDistanceShow((DistanceUtil.transferDistance(
					user.getDistance()==null?new BigDecimal("0").doubleValue():user.getDistance().doubleValue())));
			// 处理在线时长
			if(null != user.getLoginTime()) {
				user.setLoginTimeShow(DateUtils.getLoginTimeHome(user.getLoginTime()));
			}
			// 处理虚拟用户距离
			if(3 == user.getEnabled()) {
				if(user.getVirtuallyDistance() > 0) {
					user.setDistanceShow(user.getVirtuallyDistance()+"km");
				}else {
					user.setDistanceShow(DistanceUtil.getVirtuallyDistance());
				}
				if(StringUtils.isNotEmpty(user.getEmUsername())) {
					user.setLoginTimeShow("在线");
				}else {
					user.setLoginTimeShow("最近活跃");
				}
				if(StringUtils.isNotEmpty(user.getVirtuallyStatus())) {
					user.setLoginTimeShow(user.getVirtuallyStatus());
				}
			}
			user.setDistanceShow("");
			//处理关注状态
			if(loginUserId.longValue() == userId.longValue()) {
				user.setConcernStatus(-1);
			}
			// 相册
			List<FileAttachment> fileList = fileAttachmentMapper.selectList(new LambdaQueryWrapper<FileAttachment>()
					.eq(FileAttachment::getFileModule, "photo").eq(FileAttachment::getUserId, userId));
			if(CollectionUtil.isNotEmpty(fileList)) {
				user.setPhotoList(fileList);
				user.setRealPersonAuth(1);
			}
			// 是否解锁微信
			if(StringUtils.isNotEmpty(user.getWechat())) {
				user.setIsBindWechat(1);
				Integer wechatCount = userUnlockWechatMapper.selectCount(new LambdaQueryWrapper<UserUnlockWechat>().eq(UserUnlockWechat::getUserId, loginUserId)
						.eq(UserUnlockWechat::getToUserId, userId).eq(UserUnlockWechat::getStatus, 1));
				if(wechatCount > 0) {
					user.setIsWehcat(1);
				}else {
					user.setWechat(CommonUtil.hiddenWechat(user.getWechat()));
				}
			}
			// 城市 city
			if(3 != currUser.getEnabled()) {
				user.setCity("");
			}
			// 当前用户为3时展示详细地址以及用户VIP开通的支付方式
			user.setEnabled(currUser.getEnabled());
			if(null != user.getVip() && 1 == user.getVip()) {
				// 
				OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
						.eq(OrderInfo::getPayUserId, user.getUserId()).eq(OrderInfo::getOrderType, 1)
						.eq(OrderInfo::getOrderStatus, 1).orderByDesc(OrderInfo::getUpdateTime)
						.select(OrderInfo::getId,OrderInfo::getPayType).last("limit 1"));
				if(null != orderInfo) {
					user.setVipPayType(Integer.valueOf(orderInfo.getPayType()));
				}
			}

			// 增加访问记录
			taskAsync.addViewRecord(loginUserId, userId, 0);
			return AjaxResult.success(user);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult qryUserPhoto(Long userId, HttpServletRequest request) {
		try {
			List<FileAttachment> fileList = fileAttachmentMapper.selectList(new LambdaQueryWrapper<FileAttachment>().eq(FileAttachment::getUserId, userId)
					.eq(FileAttachment::getFileModule, ProjectConstant.FileModule.PHOTO));
			return AjaxResult.success(fileList);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	/**
	 * 	获取用户ID
	 * @return
	 */
	private Long getLoginUserId() {
		Object object = RequestContext.get("userInfo");
		if(null == object) {
			return null;
		}
		JWTUser jwtUser = (JWTUser) object;
		if(null == jwtUser || null == jwtUser.getId()) {
			return null;
		}
		return jwtUser.getId();
	}

	@Override
	public AjaxResult concernOperation(Long userId, Integer type) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		try {
			if(loginUserId.longValue() == userId.longValue()) {	return AjaxResult.error("自己不能关注自己哦");}
			if(!redisUtil.setIfAbsentCustom("concernOperation:"+loginUserId,1000)) { return AjaxResult.error("操作过于频繁");	}
			List<UserConcern> list = new ArrayList<UserConcern>();
			UserConcern userConcern = userConcernService.getOne(new LambdaQueryWrapper<UserConcern>().eq(UserConcern::getUserId, loginUserId).eq(UserConcern::getConcernedUserId, userId));
			if(null != userConcern ) {
				if(1 == type) {//关注
					if(2 != userConcern.getType()) {
						return AjaxResult.error("你已经关注Ta了");
					}
					UserConcern toUserConcern = userConcernService.getOne(new LambdaQueryWrapper<UserConcern>().eq(UserConcern::getUserId, userId).eq(UserConcern::getConcernedUserId, loginUserId));
					userConcern.setType(3);
					toUserConcern.setType(3);
					list.add(userConcern);
					list.add(toUserConcern);
					userConcernService.updateBatchById(list);
				}else {//取关
					UserConcern toUserConcern = userConcernService.getOne(new LambdaQueryWrapper<UserConcern>().eq(UserConcern::getUserId, userId).eq(UserConcern::getConcernedUserId, loginUserId));
					if(3 == userConcern.getType()) {
						userConcern.setType(2);
						toUserConcern.setType(1);
						list.add(userConcern);
						list.add(toUserConcern);
						userConcernService.updateBatchById(list);
					}else if(1 == userConcern.getType()) {
						List<Long> ids = new ArrayList<Long>();
						ids.add(userConcern.getId());
						ids.add(toUserConcern.getId());
						userConcernService.removeByIds(ids);
					}
				}
			}else {
				//关注
				userConcern = new UserConcern();
				userConcern.setUserId(loginUserId);
				userConcern.setConcernedUserId(userId);
				userConcern.setType(1);
				UserConcern toUserConcern = new UserConcern();
				toUserConcern.setUserId(userId);
				toUserConcern.setConcernedUserId(loginUserId);
				toUserConcern.setType(2);
				list.add(userConcern);
				list.add(toUserConcern);
				userConcernService.saveBatch(list);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult delUserPhoto(Long photoId, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			fileAttachmentMapper.deleteById(photoId);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult addUserPhoto(List<String> photoList, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(CollectionUtil.isNotEmpty(photoList)) {
				fileAttachmentMapper.delete(new LambdaQueryWrapper<FileAttachment>().eq(FileAttachment::getUserId, loginUserId)
						.eq(FileAttachment::getFileModule, ProjectConstant.FileModule.PHOTO));
				photoList.stream().forEach(photo ->{
					FileAttachment file = new FileAttachment();
					file.setUserId(loginUserId);
					file.setFileModule(ProjectConstant.FileModule.PHOTO);
					file.setFilePath(photo);
					fileAttachmentMapper.insert(file);
				});
			}
			// TODO 添加标签
			//taskAsync.taggingRealPerson(loginUserId, file.getId(), photoUrl);
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("photoList", photoList);
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult qryUserInfo(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			AppUserInfo qryUserInfo = userMapper.qryUserInfo(loginUserId);
			if(null == qryUserInfo) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(2 == qryUserInfo.getEnabled()) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = new User();
			user.setId(loginUserId);
			user.setLoginTime(new Date());
			taskAsync.updateUserInfo(user);
			taskAsync.updateUserStatus(loginUserId);
			return AjaxResult.success(qryUserInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult editUserInfo(AppUserInfo userInfo, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			//检查昵称是否存在
			Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getNickName, userInfo.getNickName()).ne(User::getId, userInfo.getUserId()));
			if(null != count && count > 0) {
				return AjaxResult.error("昵称已存在请更换");
			}
			User one = userMapper.selectOne(new LambdaQueryWrapper<User>()
					.eq(User::getId, userInfo.getUserId()).select(User::getId,User::getNickName));
			
			User user = new User();
			user.setId(loginUserId);
			user.setHeadPic(userInfo.getHeadPic());
			if(null != one && StringUtils.isEmpty(one.getNickName())) {
				user.setNickName(userInfo.getNickName());
			}
			//user.setSex(userInfo.getSex());
			user.setHeight(userInfo.getHeight());
			user.setBodyWeight(userInfo.getBodyWeight());
			if(null != userInfo.getCityCode()) {
				user.setLoginCityCode(userInfo.getCityCode());
			}
			if(StringUtils.isNotEmpty(userInfo.getCity())) {
				user.setLoginCityName(userInfo.getCity());
			}
			if(StringUtils.isNotEmpty(userInfo.getBirthdayShow())) {
				user.setBirthday(DateUtil.formatDate("yyyy-MM-dd", userInfo.getBirthdayShow()));
			}
			user.setLable(userInfo.getLable());
			user.setSignature(userInfo.getSignature());
			user.setVideo(userInfo.getVoice());
			user.setConstellation(userInfo.getConstellation());
			userMapper.updateById(user);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult userPersonal(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			AppUserPersonal userPersonal = userMapper.userPersonal(loginUserId);
			if(null == userPersonal) {
				return AjaxResult.error(50010,"请重新登录");
			}
			// 处理年龄
			if(null != userPersonal.getBirthday()) {
				userPersonal.setAge(CommonUtil.getAge(userPersonal.getBirthday()));
			}
			if(null != userPersonal.getVipTime() && DateUtils.isOverdue(new Date(), userPersonal.getVipTime())) {
				userPersonal.setVip(1);
				userPersonal.setVipExpireTime(DateUtils.format(userPersonal.getVipTime(), "yyyy.MM.dd"));
			}else {
				// 修改用户信息
				userPersonal.setVip(0);
				User user = new User();
				user.setId(loginUserId);
				user.setVip(0);
				user.setMacAddress(request.getHeader("clientType"));
				user.setDeviceName(request.getHeader("deviceName"));
				user.setAge(userPersonal.getAge());
				taskAsync.updateUserInfo(user);
			}
			if(StringUtils.isNotEmpty(userPersonal.getWechat())) {
				userPersonal.setWechat(CommonUtil.hiddenWechat(userPersonal.getWechat()));
			}
			/**
			 *  (select count(0) from t_user_concern where user_id = u.id and type != 2) follow,
			 *	(select count(0) from t_user_concern where user_id = u.id and type != 1) fans,
			 */
			// 关注
			userPersonal.setFollowCount(userConcernService.count(new LambdaQueryWrapper<UserConcern>().eq(UserConcern::getUserId, loginUserId).ne(UserConcern::getType, 2)));
			userPersonal.setFansCount(0);
			// 粉丝
			List<UserConcern> list = userConcernService.list(new LambdaQueryWrapper<UserConcern>().eq(UserConcern::getUserId, loginUserId).ne(UserConcern::getType, 1));
			if(CollectionUtil.isNotEmpty(list)) {
				List<Long> collect = list.stream().map(c -> c.getConcernedUserId()).collect(Collectors.toList());
				Integer selectCount = userMapper.selectCount(new LambdaQueryWrapper<User>().in(User::getId, collect).eq(User::getVip, 1));
				userPersonal.setFansCount(selectCount);
			}
			// 动态
			userPersonal.setDynamicCount(userDynamicMapper.selectCount(new LambdaQueryWrapper<UserDynamic>().eq(UserDynamic::getStatus, 0).eq(UserDynamic::getUserId, loginUserId)));
			// 约玩
			userPersonal.setPlayCount(userPartyMapper.selectCount(new LambdaQueryWrapper<UserParty>().eq(UserParty::getStatus, 0).eq(UserParty::getUserId, loginUserId)));
			//			// 访客
			//			userPersonal.setVisitorCount(userViewRecordMapper.selectCount(new LambdaQueryWrapper<UserViewRecord>().eq(UserViewRecord::getViewedUserId, loginUserId).eq(UserViewRecord::getStatus, 0)
			//					.eq(UserViewRecord::getEnabled, 1)));
			//			// 足迹
			//			userPersonal.setFootprintCount(userViewRecordMapper.selectCount(new LambdaQueryWrapper<UserViewRecord>().eq(UserViewRecord::getUserId, loginUserId).eq(UserViewRecord::getStatus, 0)
			//					.eq(UserViewRecord::getEnabled, 1)));

			// 环信账号
			UserExtend extend = userExtendMapper.selectOne(new LambdaQueryWrapper<UserExtend>().eq(UserExtend::getUserId, loginUserId));
			if(null != extend && StringUtils.isNotEmpty(extend.getEmUsername()) && StringUtils.isNotEmpty(extend.getEmPassword())) {
				userPersonal.setEmUsername(extend.getEmUsername());
				userPersonal.setEmPassword(extend.getEmPassword());
			}

			// 统计新增
			Object object = redisUtil.get(loginUserId+"-Statistics");
			if(null == object) {
				redisUtil.set(loginUserId+"-Statistics",loginUserId,DateUtils.getMorningTime()+new Random().nextInt(10));
				userDataStatisticsService.addStatistics(1, 0);
			}
			// 是否已经设置 青少年模式密码
			if(StringUtils.isNotEmpty(userPersonal.getYoungPwd())) {
				userPersonal.setIsYoungPwd(1);
			}
			return AjaxResult.success(userPersonal);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult blockOrunBlock(Long userId, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			UserBlacklist black = userBlacklistMapper.selectOne(new LambdaQueryWrapper<UserBlacklist>().eq(UserBlacklist::getUserId, loginUserId).eq(UserBlacklist::getPullBlackUserId, userId));
			if(null == black) {
				black = new UserBlacklist();
				black.setUserId(loginUserId);
				black.setPullBlackUserId(userId);
				black.setEnabled(ProjectConstant.COMMON_STATUS_AVAILABLE);
				black.setCreateTime(new Date());
				userBlacklistMapper.insert(black);
				taskAsync.blockOrunBlock(loginUserId, userId, 1);
			}else {
				if (black != null) {
					userBlacklistMapper.deleteById(black.getId());
				}
				taskAsync.blockOrunBlock(loginUserId, userId, 2);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult myBlacklist(Integer pageNo, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			pageNo = (pageNo -1) * 10;
			List<AppWhoHaveIsee> myBlacklist = userBlacklistMapper.myBlacklist(loginUserId, pageNo);
			myBlacklist.parallelStream().forEach(black ->{
				//处理年龄
				if(black.getBirthday() != null) {
					black.setAge(CommonUtil.getAge(black.getBirthday()));
				}else {
					black.setAge(22);
				}
				// 处理在线时长
				if(null != black.getLoginTime()) {
					black.setLoginTimeShow(DateUtils.getLoginTime(black.getLoginTime()));
				}
			});
			return AjaxResult.success(myBlacklist);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult myWallet(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Map<String,Object> map = new HashMap<String, Object>();
			String balanceAmount = userTotalCapitalMapper.getAmountByUserId(loginUserId);
			UserTotalCapital initData = userTotalCapitalService.initData("1", loginUserId);
			if(StringUtils.isEmpty(balanceAmount)) {
				balanceAmount = "0";
			}
			map.put("balanceAmount",balanceAmount);	// 余额
			map.put("incomeAmount", (initData.getTotalAmount().subtract(initData.getFrozenAmount()))); // 总收益
			//			map.put("waitAmount", initData.getWaitAmount());	// 待提现
			//			map.put("canAmount", (initData.getCanAmount().subtract(initData.getFrozenAmount()))); // 可提现
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}

	}

	@Override
	public AjaxResult myCorrelationList(Integer type, Integer pageNo) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			// 1=粉丝 2=关注 3=访客 4=足迹
			if(1 == type || 2 == type) {
				IPage<AppWhoHaveIsee> list = userConcernService.myFollowOrFans(new Page<AppWhoHaveIsee>().setCurrent(pageNo).setSize(10),loginUserId, type, pageNo);
				List<AppWhoHaveIsee> records = list.getRecords();
				records.stream().forEach(user ->{
					//处理年龄
					if(user.getBirthday() != null) {
						user.setAge(CommonUtil.getAge(user.getBirthday()));
					}else {
						user.setAge(22);
					}
				});
				return AjaxResult.success(records);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getConsultantAuthInfo(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			AppConsultantAuth consultantAuth = new AppConsultantAuth();
			consultantAuth.setUserId(loginUserId);
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getName,User::getIdCard
					,User::getWechat,User::getIdCardFront,User::getIdCardBack,User::getIsConsultantAuth,User::getRefuseReason,User::getCertificate));
			if(null != user) {
				consultantAuth.setName(user.getName());
				consultantAuth.setIdCard(user.getIdCard());
				consultantAuth.setWechat(user.getWechat());
				consultantAuth.setIdCardFront(user.getIdCardFront());
				consultantAuth.setIdCardBack(user.getIdCardFront());
				consultantAuth.setIsConsultantAuth(user.getIsConsultantAuth());
				consultantAuth.setRefuseReason(user.getRefuseReason());
				consultantAuth.setCertificate(user.getCertificate());
			}
			return AjaxResult.success(consultantAuth);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}

	}

	@Override
	public AjaxResult editConsultantAuthInfo(AppConsultantAuth consultantAuth, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = new User();
			user.setId(loginUserId);
			if(StringUtils.isNotEmpty(consultantAuth.getName())) {
				user.setName(consultantAuth.getName());
			}
			if(StringUtils.isNotEmpty(consultantAuth.getIdCard())) {
				user.setIdCard(consultantAuth.getIdCard());
			}
			if(StringUtils.isNotEmpty(consultantAuth.getWechat())) {
				user.setWechat(consultantAuth.getWechat());
			}
			if(StringUtils.isNotEmpty(consultantAuth.getIdCardFront())) {
				user.setIdCardFront(consultantAuth.getIdCardFront());
			}
			if(StringUtils.isNotEmpty(consultantAuth.getIdCardBack())) {
				user.setIdCardBack(consultantAuth.getIdCardBack());
			}
			if(StringUtils.isNotEmpty(consultantAuth.getCertificate())) {
				user.setCertificate(consultantAuth.getCertificate());
			}
			user.setIsConsultantAuth(0);
			userMapper.updateById(user);
			// 推送系统消息
			taskAsync.sendSystemMsg(loginUserId, 0l, 18, "咨询师认证", "您的咨询师认证已提交，请您耐心等待！");

			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult setLableOrVoice(AppUserDetail user, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User currUser = new User();
			currUser.setId(loginUserId);
			if(StringUtils.isNotEmpty(user.getLable())) {
				currUser.setLable(user.getLable());
			}
			if(StringUtils.isNotEmpty(user.getVoice())) {
				currUser.setVoice(user.getVoice());
			}
			if(StringUtils.isNotEmpty(user.getServiceType())) {
				currUser.setServiceType(user.getServiceType());
			}
			userMapper.updateById(currUser);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult addConsultantProject(UserProject userProject, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(null != userProject.getId()) {
				userProject.setStatus(1);
				userProjectMapper.updateById(userProject);
			}else {
				userProject.setUserId(loginUserId);
				userProject.setStatus(1);
				userProjectMapper.insert(userProject);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getConsultantProjectDetail(Long id, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			UserProject userProject = userProjectMapper.selectById(id);
			if(null == userProject) {
				return AjaxResult.error("项目不存在");
			}
			if(StringUtils.isNotEmpty(userProject.getImg())) {
				userProject.setImgList(Arrays.asList(userProject.getImg().split(",")));
				userProject.setImg("");
			}
			return AjaxResult.success(userProject);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult userOrderEvaluateList(Long toUserId, Integer pageNo, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			//pageNo = (pageNo -1)*10;
			IPage<AppOrderEvaluateDTO> orderEvaluateList = orderEvaluateMapper.getOrderEvaluateList(new Page<AppOrderEvaluateDTO>().setCurrent(pageNo).setSize(10), toUserId);
			orderEvaluateList.getRecords().parallelStream().forEach(eva ->{
				eva.setEvaltateTime(DateUtils.getTimeCompareStringDynamic(eva.getTime()));
			});
			return AjaxResult.success(orderEvaluateList.getRecords());
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getRechargeRecord(Integer pageNo) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Page<UserCapitalFlow> page = userCapitalFlowService.page(new Page<UserCapitalFlow>().setCurrent(pageNo).setSize(10), new LambdaQueryWrapper<UserCapitalFlow>()
					.eq(UserCapitalFlow::getUserId, loginUserId).eq(UserCapitalFlow::getType, 2).eq(UserCapitalFlow::getBusinessType, 4)
					.orderByDesc(UserCapitalFlow::getCreateTime));
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total",page.getTotal());
			map.put("list", page.getRecords());
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getConsultantProjectList(Integer pageNo, String lable) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			IPage<UserProject> page = userProjectMapper.getConsultantProjectList(new Page<UserProject>().setCurrent(pageNo).setSize(10), lable);
			Map<String, Object> map = new HashMap<String, Object>();
			page.getRecords().stream().forEach(pro ->{
				if(null != pro.getBirthday()) {
					pro.setAge(CommonUtil.getAge(pro.getBirthday()));
				}else {
					pro.setAge(22);
				}
				if(1 == pro.getOnlineStatus() ) {
					pro.setOnlineStatus(3);
				}else {
					pro.setOnlineStatus(DateUtils.getTimeCompareStringold(pro.getLoginTime()));
				}
			});
			map.put("total",page.getTotal());
			map.put("list", page.getRecords());
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult whoHaveIsee(AppUserParam param, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			param.setPageNo((param.getPageNo() -1)*10);
			Map<String,Object> map = new HashMap<String, Object>();
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
					.select(User::getId,User::getHideView,User::getVip,User::getLoginCityName,User::getLoginPointX,User::getLoginPointY));
			if(null == user) {
				return AjaxResult.error(600,"请重新登录");
			}
			if(null == param.getLatitude() || null == param.getLongitude()) {
				if(null == user.getLoginPointX() || null == user.getLoginPointY()) {
					param.setLongitude(new BigDecimal("112"));
					param.setLatitude(new BigDecimal("28"));
				}else {
					param.setLongitude(user.getLoginPointX());
					param.setLatitude(user.getLoginPointY());
				}
			}
			if(2 == param.getType() && (user.getVip() == null || user.getVip() == 0 )) {
				Integer qrySeeCount = userMapper.qrySeeCount(loginUserId, user.getLoginCityName(), 1);
				Integer qrySeeCount1 = userMapper.qrySeeCount(loginUserId, user.getLoginCityName(), 2);
				//				if(qrySeeCount > 0) {
				//					map.put("hereSee", qrySeeCount);//正在查看人数
				//				}
				//				if(qrySeeCount1 > 0) {
				//					map.put("citySee", qrySeeCount1);//同城查看人数
				//				}
				map.put("hereSee", qrySeeCount+15);//正在查看人数
				map.put("citySee", qrySeeCount1+18);//同城查看人数
			}
			List<AppWhoHaveIsee> list = userMapper.whoHaveIsee(param.getLongitude(), param.getLatitude(), loginUserId, param.getPageNo(),param.getType());
			if(CollectionUtil.isEmpty(list)) list = new ArrayList<AppWhoHaveIsee>();
			list.parallelStream().forEach(appWhoHaveIsee ->{
				if(2 == param.getType()) { // 谁看过我
					List<FileAttachment> fileList = fileAttachmentMapper.selectList(new LambdaQueryWrapper<FileAttachment>().eq(FileAttachment::getUserId, appWhoHaveIsee.getUserId())
							.eq(FileAttachment::getFileModule, ProjectConstant.FileModule.PHOTO).select(FileAttachment::getId,FileAttachment::getFilePath));
					if(CollectionUtil.isNotEmpty(fileList)) {
						appWhoHaveIsee.setPhotos(fileList.stream().map(FileAttachment::getFilePath).collect(Collectors.toList()));
					}
				}
				//处理年龄
				if(appWhoHaveIsee.getBirthday() != null) {
					appWhoHaveIsee.setAge(CommonUtil.getAge(appWhoHaveIsee.getBirthday()));
				}else {
					appWhoHaveIsee.setAge(22);
				}
				//距离 判断用户是否设置了保密
				appWhoHaveIsee.setDistanceShow((DistanceUtil.transferDistance(appWhoHaveIsee.getDistance()==null?new BigDecimal("0").doubleValue():appWhoHaveIsee.getDistance().doubleValue())));

				// 处理在线时长
				if(null != appWhoHaveIsee.getLoginTime()) {
					appWhoHaveIsee.setLoginTimeShow(DateUtils.getLoginTime(appWhoHaveIsee.getLoginTime()));
				}
				if(1 == param.getType()) {
					appWhoHaveIsee.setViewTime(DateUtils.getTimeCompareStringFootprint(appWhoHaveIsee.getUpdateTime())+"看过Ta");
				}
			});
			map.put("list", list);
			// 隐私访问状态
			map.put("isInvisible", 0);
			if(null != user) {
				map.put("isInvisible", user.getHideView()==null?0:user.getHideView());
			}
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	/**
	 * 	添加解锁微信记录
	 */
	private void addUnlockWechatRecord(Long userId,Long toUserId,String wechat) {
		UserUnlockWechat unlockWechat = new UserUnlockWechat();
		unlockWechat.setUserId(userId);
		unlockWechat.setToUserId(toUserId);
		unlockWechat.setWechat(wechat);
		unlockWechat.setStatus(1);
		userUnlockWechatMapper.insert(unlockWechat);
		// 发送解锁微信消息
		taskAsync.sendSystemMsg(toUserId, userId, 1, "", "");
	}

	/**
	 * 	添加解锁聊天记录
	 */
	private void addUnlockChatRecord(Long userId,Long toUserId) {
		UserConversationRecord record = new UserConversationRecord();
		record.setLaunchUserId(userId);
		record.setReplyUserId(toUserId);
		record.setCreateTime(new Date());
		userConversationRecordMapper.insert(record);
	}

	@Autowired
	private PriceSettingMapper priceSettingMapper;
	/***
	 * 	是否开启审核模式
	 */
	private boolean isExamineMode() {
		PriceSetting set = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "审核设置").select(PriceSetting::getId,PriceSetting::getEnabled)
				.last("limit 1"));
		if(null != set && 1 == set.getEnabled()) {
			return true;
		}
		return false;
	}

	@Override
	@Transactional
	public AjaxResult unlockUserWechat(AppUserInfo userInfo) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(!redisUtil.setIfAbsentCustom("unlockUserWechat:"+userInfo.getUserId()+"-"+loginUserId,1000)) {
				return AjaxResult.error("休息一下吧~");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
					.select(User::getId,User::getUnlockWechat,User::getVip,User::getVipLevel));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User toUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userInfo.getUserId())
					.select(User::getId,User::getWechat,User::getVip,User::getVipLevel));
			if(null == toUser || StringUtils.isEmpty(toUser.getWechat())) {
				return AjaxResult.error("对方暂未设置微信号");
			}
			Map<String,Object> map = new HashMap<String, Object>();
			Integer wechatCount = userUnlockWechatMapper.selectCount(new LambdaQueryWrapper<UserUnlockWechat>().eq(UserUnlockWechat::getUserId, loginUserId)
					.eq(UserUnlockWechat::getToUserId, userInfo.getUserId()).eq(UserUnlockWechat::getStatus, 1));
			if(wechatCount > 0) {
				map.put("wechat", toUser.getWechat());
				return AjaxResult.success(map);
			}
			// 1=第一次点击 2=付款
			if(1 == userInfo.getType()) {
				if(toUser.getVip() > 0) {
					if(user.getVipLevel() >= toUser.getVipLevel()) {
						if(user.getUnlockWechat() > 0) {
							user.setUnlockWechat(user.getUnlockWechat()-1);
							userMapper.updateById(user);
							map.put("wechat", toUser.getWechat());
							addUnlockWechatRecord(loginUserId, userInfo.getUserId(), toUser.getWechat());
							return AjaxResult.success(map);
						}
					}
					return AjaxResult.error(50103,"解锁次数已用尽,升级VIP方可解锁");

				}else {
					if(user.getUnlockWechat() > 0) {
						user.setUnlockWechat(user.getUnlockWechat()-1);
						userMapper.updateById(user);
						map.put("wechat", toUser.getWechat());
						addUnlockWechatRecord(loginUserId, userInfo.getUserId(), toUser.getWechat());
						return AjaxResult.success(map);
					}else {
						return AjaxResult.error(50103,"解锁次数已用尽,升级VIP方可解锁");
					}

				}

				//				if(user.getUnlockWechat() > 0) {
				//					user.setUnlockWechat(user.getUnlockWechat()-1);
				//					userMapper.updateById(user);
				//					map.put("wechat", toUser.getWechat());
				//					addUnlockWechatRecord(loginUserId, userInfo.getUserId(), toUser.getWechat());
				//					return AjaxResult.success(map);
				//				}else { 
				//					String price = "20";
				//					Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKWECHATPRICE);
				//					if(null != object ) {
				//						price = new BigDecimal(object.toString()).stripTrailingZeros().toPlainString();
				//					}
				//					if(user.getVip() > 0) {
				//						return AjaxResult.error(50101,"请单次购买",price);
				//					}else {
				//						return AjaxResult.error(50102,"请选择开通VIP或者单次购买",price);
				//					}
				//				}
			}else {
				//				PriceSetting one = priceSettingService.getOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "解锁微信")
				//						.select(PriceSetting::getId,PriceSetting::getCurrentPrice));
				//				if(null == one ) {
				//					return AjaxResult.error("请选择解锁类型");
				//				}
				//				Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKWECHATPRICE);
				//				if(null == object ) {
				//					return AjaxResult.error("请选择解锁类型");
				//				}
				//				BigDecimal price = new BigDecimal(object.toString());
				//				// 查询用户余额
				//				UserTotalCapital userTotalCapital = userTotalCapitalService.initData("3", loginUserId);
				//				if(userTotalCapital.getTotalAmount().compareTo(price) == -1) {
				//					return AjaxResult.error(50011,"钻石不足，请先充值钻石再使用");
				//				}
				//				userTotalCapitalService.initUserTotalCapital("3", loginUserId, price, 0);
				//				taskAsync.addUserCapitalFlow(loginUserId, userInfo.getUserId(), 5, price, 3, 1);
				//				map.put("wechat", toUser.getWechat());
				//				addUnlockWechatRecord(loginUserId, userInfo.getUserId(), toUser.getWechat());
				return AjaxResult.error("暂不支持");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	@Transactional
	public AjaxResult unlockUserChat(AppUserInfo userInfo) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(!redisUtil.setIfAbsentCustom("unlockUserChat:"+userInfo.getUserId()+"-"+loginUserId,1000)) {
				return AjaxResult.error("休息一下吧~");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
					.select(User::getId,User::getChatCount,User::getVip,User::getEnabled));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}

			User toUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userInfo.getUserId())
					.select(User::getId,User::getChatCount,User::getVip));
			if(null == toUser) {
				return AjaxResult.error("对方用户不存在");
			}

			Map<String,Object> map = new HashMap<String, Object>();
			// 虚拟用户不做限制
			if(3 == user.getEnabled()) {
				return AjaxResult.success(map);
			}
			Integer count = userConversationRecordMapper.selectCount(new LambdaQueryWrapper<UserConversationRecord>().eq(UserConversationRecord::getLaunchUserId, loginUserId)
					.eq(UserConversationRecord::getReplyUserId, userInfo.getUserId()));
			if(count > 0) {
				return AjaxResult.success("已解锁,可直接聊天");
			}
			// 1=第一次点击 2=付款
			if(1 == userInfo.getType()) {
				if(user.getChatCount() > 0) {
					if(0 == toUser.getVip()) {
						return AjaxResult.error(50104,"对方不是VIP不可发起聊天");
					}
					user.setChatCount(user.getChatCount()-1);
					userMapper.updateById(user);
					addUnlockChatRecord(loginUserId, userInfo.getUserId());
					return AjaxResult.success(map);
				}else { 
					String price = "20";
					Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKCHATPRICE);
					if(null != object ) {
						price = new BigDecimal(object.toString()).stripTrailingZeros().toPlainString();
					}
					if(user.getVip() > 0) {
						return AjaxResult.error(50101,"请单次购买",price);
					}else {
						return AjaxResult.error(50102,"请选择开通VIP或者单次购买",price);
					}
				}
			}else {
				//				PriceSetting one = priceSettingService.getOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "解锁聊天")
				//						.select(PriceSetting::getId,PriceSetting::getCurrentPrice));
				//				if(null == one ) {
				//					return AjaxResult.error("请选择解锁类型");
				//				}
				Object object = redisUtil.get(ProjectConstant.platformConstant.UNLOCKCHATPRICE);
				if(null == object ) {
					return AjaxResult.error("请选择解锁类型");
				}
				BigDecimal price = new BigDecimal(object.toString());
				// 查询用户余额
				UserTotalCapital userTotalCapital = userTotalCapitalService.initData("3", loginUserId);
				if(userTotalCapital.getTotalAmount().compareTo(price) == -1) {
					return AjaxResult.error(50011,"花蜜不足，请先充值花蜜再使用");
				}
				userTotalCapitalService.initUserTotalCapital("3", loginUserId, price, 0);
				taskAsync.addUserCapitalFlow(loginUserId, userInfo.getUserId(), 6, price, 3, 1);
				addUnlockChatRecord(loginUserId, userInfo.getUserId());
			}
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult setWechat(String wechat, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = new User();
			user.setId(loginUserId);
			user.setWechat(wechat);
			userMapper.updateById(user);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult setVoice(String voice, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = new User();
			user.setId(loginUserId);
			user.setVoice(voice);
			userMapper.updateById(user);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getUnlockWechatList(Integer pageNo) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			IPage<AppWechatVO> page = userMapper.getUnlockWechatList(new Page<AppWechatVO>().setCurrent(pageNo).setSize(10), loginUserId);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total",page.getTotal());
			map.put("list", page.getRecords());
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getUserLocate(Long userId) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User touser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userId).select(User::getId,User::getEnabled,User::getVirtuallyDistance));
		if(null == touser) {
			return AjaxResult.error("用户不存在");
		}
		User cuuser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getLoginPointX,User::getLoginPointY));
		if(null == cuuser) {
			return AjaxResult.error(50010,"请重新登录");
		}

		BigDecimal distance = userMapper.getUserLocate(userId, cuuser.getLoginPointX(),cuuser.getLoginPointY());
		// 处理距离
		String distanceShow = (DistanceUtil.transferDistance(
				distance==null?new BigDecimal("0").doubleValue():distance.doubleValue()));

		// 处理虚拟用户距离
		if(3 == touser.getEnabled()) {
			if(null != touser.getVirtuallyDistance() && touser.getVirtuallyDistance() > 0) {
				distanceShow = touser.getVirtuallyDistance()+"km";
			}else {
				distanceShow = DistanceUtil.getVirtuallyDistance();
			}
		}
		distanceShow = "";
		return AjaxResult.success("获取成功",distanceShow);
	}



	@Override
	public AjaxResult updateDeviceId(String deviceId) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		UserExtend extend = userExtendMapper.selectOne(new LambdaQueryWrapper<UserExtend>().eq(UserExtend::getUserId, loginUserId));
		if(null == extend) {
			extend = new UserExtend();
			extend.setUserId(loginUserId);
			extend.setDeviceId(deviceId);
			userExtendMapper.insert(extend);
		}else {
			extend.setDeviceId(deviceId);
			userExtendMapper.updateById(extend);
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult resetPassword(String mobile, String mobileCode, String password) {
		boolean right = false;
		Object savedMobile = redisUtil.get(ProjectConstant.RedisKey.MOBILE_CODE.getKeyPrefix() +"_"+ 7 + "_" + mobileCode);
		log.info("取缓存中的验证码信息:{}",JSON.toJSONString(savedMobile));
		if (savedMobile != null && mobile.equals(savedMobile.toString())) {
			right = true;
		}
		if(exampleCode.equals(mobileCode)){
			right = true;
		}
		if (!right) {
			return AjaxResult.error("验证码不一致");
		}
		User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone", mobile));
		if(null == user) {
			return AjaxResult.error("该手机号码未注册");
		}
		user.setPassword(Md5Utils.hash(password));
		userMapper.updateById(user);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult setTeenageMode(Integer isYoung, String youngPwd) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if(StringUtils.isEmpty(youngPwd)) {
			return AjaxResult.error("请输入密码");	
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getYoungPwd));
		if(null == user) return AjaxResult.error(50010,"请重新登录");
		if(1 == isYoung) {
			if(StringUtils.isNotEmpty(user.getYoungPwd())) {
				// 验证
				if(!user.getYoungPwd().equals(Md5Utils.hash(youngPwd))) {
					return AjaxResult.error("密码不正确");
				}
			}else {
				// 设置
				user.setYoungPwd(Md5Utils.hash(youngPwd));
			}
		}else {
			if(!Md5Utils.hash(youngPwd).equals(user.getYoungPwd())) {
				return AjaxResult.error("密码不正确");
			}
		}
		user.setIsYoung(isYoung);
		userMapper.updateById(user);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult checkUserIsMsgSend(HttpServletRequest request,Long toUserId) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
				.select(User::getId,User::getVip,User::getVipExpireTime,User::getMessageCount,User::getEnabled,User::getVipLevel));
		if(null == user) {
			return AjaxResult.error(50010,"请重新登录");
		}
		try {
			String key = "isMsgSend-"+user.getId();
			if(redisUtil.hasKey(key)) {
				redisUtil.set(key, Integer.valueOf(redisUtil.get(key).toString())+1);
			}else {
				redisUtil.set(key, 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 虚拟用户不做限制
		if(3 == user.getEnabled()) {
			return AjaxResult.success();
		}
		if(null != user.getVipExpireTime() && DateUtils.isOverdue(new Date(), user.getVipExpireTime())) {
			user.setVip(1);
		}
		if(0 == user.getVip()) {
			if(user.getMessageCount() <= 0 ) {
				return AjaxResult.error(50102,"聊天次数已用尽,开通VIP方可续聊");
			}else {
				userMapper.updMsgCount(user.getId());
			}
		}else { // 是VIP 则判断 对方的VIP等级
			if(null != toUserId) {
				User toUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
						.select(User::getId,User::getVip,User::getVipExpireTime,User::getMessageCount,User::getEnabled,User::getVipLevel));
				if(null != toUser.getVipExpireTime() && DateUtils.isOverdue(new Date(), toUser.getVipExpireTime())) {
					toUser.setVip(1);
				}
				if(1 == toUser.getVip()) {
					if(user.getVipLevel() < toUser.getVipLevel()) {
						if(user.getMessageCount() <= 0 ) {
							return AjaxResult.error(50103,"聊天次数已用尽,升级VIP方可续聊");
						}
					}
				}
			}
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult getIsVip(Long toUserId) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
				.select(User::getId,User::getVip,User::getVipExpireTime,User::getVipLevel));
		if(null == user) {
			return AjaxResult.error(50010,"请重新登录");
		}
		Integer isVip = 0;
		Integer vipLevel = 1;
		if(null != user.getVipExpireTime() && DateUtils.isOverdue(new Date(), user.getVipExpireTime())) {
			isVip = 1;
			vipLevel = user.getVipLevel();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("vip", isVip);
		map.put("vipLevel", vipLevel);
		return AjaxResult.success(map);
	}

}
